package com.github.common.extend.demo.config.json.jaskson.filter;

import com.alibaba.fastjson.serializer.BeanContext;
import com.alibaba.fastjson.serializer.ContextValueFilter;
import com.github.common.extend.demo.config.json.ValueFormat;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;
import java.text.MessageFormat;
import java.util.regex.Pattern;

/**
 * @author wangjj7
 * @date 2024/4/3
 * @description
 */
public class ValueFormatValueFilter implements ContextValueFilter {

    @Override
    public Object process(BeanContext context, Object object, String name, Object value) {
        if (value == null || context == null){
            return value;
        }
        // 获取字段上的注解(注意JsonField注解会自定义name)
        Field field = context.getField();
        //修复BUG：仅仅有setter/getter方法，但是未定义Field；会出现NPE
        if(field == null){
            return value;
        }
        ValueFormat fieldAnnotation = field.getAnnotation(ValueFormat.class);
        if (fieldAnnotation == null){
            return value;
        }

        String patternStr = fieldAnnotation.pattern();
        String writeValue = fieldAnnotation.writeValue();
        String writeProperty = fieldAnnotation.writeProperty();
        String str = value.toString();

        boolean match = StringUtils.isEmpty(patternStr) ? true : Pattern.compile(patternStr).matcher(str).matches();
        if (match){
            if (StringUtils.isNotEmpty(writeValue)){
                String writeValueStr = MessageFormat.format(writeValue ,value);
                if (StringUtils.isEmpty(writeProperty) || name.equals(writeProperty)) {
                    return writeValueStr;
                }

                throw new IllegalStateException("fastjson只支持写入当前属性");
            }
        }

        return value;
    }
}
